//
//  JiaoYiPageViewController.m
//  DBAChain
//
//  Created by Evan on 2018/9/6.
//  Copyright © 2018 Evan. All rights reserved.
//

#import "JiaoYiPageViewController.h"
#import "CommonData.h"
#import <Masonry.h>
#import "JiaoYiZheTableViewCell.h"
#import "JiaoYiMMTableViewCell.h"
#import "JiaoYiSearchTabTableViewCell.h"
#import "JiaoYiMMListTableViewCell.h"
#import "JiaoYiPassWordView.h"
#import "JiaoYiSuccessViewController.h"
#import "ZheXianTableViewCell.h"
#import "HomePassWordView.h"
#import "taskJiaoYiService.h"
#import <WebKit/WebKit.h>
#import "viewPayValidate.h"
#import "taskUserManagerService.h"
#import "MeAuthenticationViewController.h"
#import "MeModifyViewController.h"
#import "MeSecurityViewController.h"
#import "JiaoYiPageHeadView.h"
#import "JiaoYiOrderViewController.h"

#define diffHeaderHeight    150;

@interface JiaoYiPageViewController ()<UITableViewDelegate,UITableViewDataSource,WKUIDelegate,UIWebViewDelegate>

@property (nonatomic,strong)    UITableView *tableView;
@property (nonatomic,strong)    HomePassWordView*   viewPassword;
@property (nonatomic,strong)    JiaoYiPassWordView *viewConfrimInfo;
@property (nonatomic,strong)    dataTransConfigInfo *dataConfig;
@property (nonatomic,strong)    viewPayValidate  *viewPayValid;
@property (nonatomic,strong)    dataUserValidateInfo    *modelUserValidate;
@property (nonatomic,strong)JiaoYiPageHeadView *headView;

@property (nonatomic,assign)    NSInteger   segmIsIndex;
///用户支付密码
@property (nonatomic,strong)    NSString *strPayPwd;

@property(nonatomic, strong) dataZheXianInfo *dataZheXian;

@end

@implementation JiaoYiPageViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self changeHeadView];
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.and.right.mas_equalTo(self.view);
        make.top.offset(-20);
        make.bottom.mas_equalTo(self.view).offset(-48);
    }];
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    
    self.hidesBottomBarWhenPushed = NO;
    if (self.tabBarController.tabBar.hidden == YES) {
        self.tabBarController.tabBar.hidden = NO;
    }
    if (self.navigationController.navigationBar.hidden == NO) {
        self.navigationController.navigationBar.hidden = YES;
    }
    
    [self loadData];
}

- (void)viewDidDisappear:(BOOL)animated{
    self.viewConfrimInfo.hidden = YES;
    self.viewPassword.hidden = YES;
    self.viewPassword.txtPwd.text = @"";
    self.strPayPwd = @"";
}


-(JiaoYiPageHeadView *)headView
{
    if (!_headView) {
        _headView = [JiaoYiPageHeadView getTopView];
        [_headView.detailbutton addTarget:self action:@selector(orderAction) forControlEvents:UIControlEventTouchUpInside];
    }
    return _headView;
}

-(viewPayValidate*)viewPayValid{
    if (!_viewPayValid ){
        _viewPayValid = [[[NSBundle mainBundle] loadNibNamed:@"viewPayValidate" owner:nil options:nil] objectAtIndex:0];
        [_viewPayValid initUI];
        [self.view addSubview:_viewPayValid];
        _viewPayValid.hidden = YES;
        [_viewPayValid mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.and.right.mas_equalTo(self.view);
            make.top.offset(60);
            make.bottom.mas_equalTo(self.view).offset(0);
        }];
        [_viewPayValid.btnSubmit addTarget:self action:@selector(btnSubmitClick:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _viewPayValid;
}

///用户验证点击完成
-(void)btnSubmitClick:(UIButton*)sender{
    if (!self.modelUserValidate.payPasswordVerify) {
        //跳转到设置支付密码页面
        [self.navigationController pushViewController:[[MeModifyViewController alloc]initWithType:1] animated:YES];
    }else if(!self.modelUserValidate.infoVerify){
        //跳转到实名认证页面
        [self.navigationController pushViewController:[MeAuthenticationViewController new] animated:YES];
    }
    //    else if(!self.modelUserValidate.safeVerify){
    //        //跳转到安全认证页面
    //        [self.navigationController pushViewController:[MeSecurityViewController new] animated:YES];
    //    }
}


-(JiaoYiPassWordView*)viewConfrimInfo{
    if (!_viewConfrimInfo) {
        _viewConfrimInfo = [[[NSBundle mainBundle] loadNibNamed:@"JiaoYiPassWordView" owner:nil options:nil] objectAtIndex:0];
        [self.view addSubview:_viewConfrimInfo];
        _viewConfrimInfo.hidden = YES;
        [_viewConfrimInfo initUI];
        [_viewConfrimInfo mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.and.right.mas_equalTo(self.view);
            make.top.offset(60);
            make.bottom.mas_equalTo(self.view).offset(0);
        }];
    }
    return _viewConfrimInfo;
}


-(HomePassWordView*)viewPassword{
    if (!_viewPassword ){
        _viewPassword = [[[NSBundle mainBundle] loadNibNamed:@"HomePassWordView" owner:nil options:nil] objectAtIndex:0];
        [_viewPassword initUI];
        [self.view addSubview:_viewPassword];
        _viewPassword.hidden = YES;
        [_viewPassword mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.and.right.mas_equalTo(self.view);
            make.top.offset(0);
            make.bottom.mas_equalTo(self.view).offset(0);
        }];
    }
    return _viewPassword;
}

#pragma mark - loaddata

- (void)loadData{
    
    [self loadTradePrice];
    [self loadOrderConfig];
}

///加载折线图数据
-(void)loadTradePrice{
    
//    [DKProgressHUD showLoading];
    [taskJiaoYiService zheTransOrder:nil success:^(dataZheXian *response, BOOL success) {
        [DKProgressHUD dismiss];
        if (success) {
            self.dataZheXian = response.data;
            NSArray<NSIndexPath*> *arrayData = [[NSArray<NSIndexPath*> alloc]initWithObjects:[NSIndexPath indexPathForRow:0 inSection:0], nil];
            [self.tableView reloadRowsAtIndexPaths:arrayData withRowAnimation:UITableViewRowAnimationNone];
        }else{
            [DKProgressHUD showErrorWithStatus:response.description];
        }

    } failture:^(NSError *error, NSString *strDescription) {
        [DKProgressHUD dismiss];
        [DKProgressHUD showErrorWithStatus:strDescription];
    }];
}

///加载配置信息
-(void)loadOrderConfig{
//    [DKProgressHUD showLoading];
    [taskJiaoYiService getTransConfig:nil success:^(dataTransConfig *response, BOOL success) {
            [DKProgressHUD dismiss];
            if (success) {
                self.dataConfig = response.data;
                [self.tableView reloadData];
            }else{
                [DKProgressHUD showErrorWithStatus:response.message];
            }
    
        } failture:^(NSError *error, NSString *strDescription) {
            [DKProgressHUD dismiss];
            [DKProgressHUD showErrorWithStatus:strDescription];
        }];
}

#pragma mark - tableivew
-(UITableView *)tableView{
    if (!_tableView) {
        self.automaticallyAdjustsScrollViewInsets = NO;
        _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, KScreenWidth, KScreenHeight) style:UITableViewStylePlain];
        [self.view addSubview:_tableView];
        _tableView.dataSource = self;
        _tableView.delegate = self;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.backgroundColor  = [UIColor clearColor];
    }
    return _tableView;
}

#pragma mark - UITableViewDelegate
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 3;
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == 0) {
        return 400;
    }else if (indexPath.row == 2){
        return 230;
    }
    return 60;
}

-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    UIView *view = [UIView new];
    view.backgroundColor = COLOR_Background;
    return view;
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 0;
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    return self.headView;
}

-(void)scrollViewDidScroll:(UIScrollView *)scrollView{
    CGFloat sectionHeaderHeight = diffHeaderHeight;
    if (scrollView.contentOffset.y<=sectionHeaderHeight&&scrollView.contentOffset.y>=0)
    {
        scrollView.contentInset = UIEdgeInsetsMake(-scrollView.contentOffset.y, 0, 0, 0);
    }
    else if (scrollView.contentOffset.y>=sectionHeaderHeight)
    {
        scrollView.contentInset = UIEdgeInsetsMake(-sectionHeaderHeight, 0, 0, 0);
    }
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return diffHeaderHeight;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.row == 0) {
        JiaoYiZheTableViewCell *cell = [JiaoYiZheTableViewCell cellWithTableView:tableView IndexPath:indexPath];
        
        
        cell.labelCNY.text = [NSString stringWithFormat:@"当前价格：%.2f CNY",self.dataZheXian.DayPriceRMB];
        cell.labelUp.text =  [NSString stringWithFormat:@"涨幅：%@",self.dataZheXian.IncreasePriceRMB] ;
        [cell initData:self.dataZheXian.modelDayList];
        cell.aaChartView.backgroundColor = [UIColor whiteColor];
        
        return cell;
    }else if(indexPath.row == 1){
        
        NSString *strIndexCell = [NSString stringWithFormat:@"JiaoYiSearchTabTableViewCell_%ld_%ld",(long)indexPath.section,(long)indexPath.row];
        JiaoYiSearchTabTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:strIndexCell];
        if (!cell) {
            [self.tableView registerClass:[JiaoYiSearchTabTableViewCell class] forCellReuseIdentifier:strIndexCell];
            cell = [tableView dequeueReusableCellWithIdentifier:strIndexCell forIndexPath:indexPath];
            [cell initUI];
        }
        [cell.segmCheck addTarget:self action:@selector(segmentValueChanged:)forControlEvents:UIControlEventValueChanged];
        return cell;
    }else if(indexPath.row == 2){
        
        NSString *strIndexCell = [NSString stringWithFormat:@"JiaoYiMMListTableViewCell_%ld_%ld",indexPath.section,indexPath.row];
        JiaoYiMMListTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:strIndexCell];
        if (!cell) {
            [self.tableView registerNib:[UINib nibWithNibName:@"JiaoYiMMListTableViewCell" bundle:nil] forCellReuseIdentifier:strIndexCell];
            cell = [tableView dequeueReusableCellWithIdentifier:strIndexCell forIndexPath:indexPath];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
        }
        ///当前用户可用余额
        cell.labelUserBalance.text = [NSString stringWithFormat:@"%.2f china-A",self.dataConfig.UserBalance ];
        cell.txtPrice.text = [NSString stringWithFormat:@"%.2f",self.dataConfig.BiDanJia];
        cell.labelCJRate.text = [NSString stringWithFormat:@"成交率：%.2f%%",self.dataConfig.UserSuccessRate];
        [cell.btnSubmitMM addTarget:self action:@selector(btnSubmitMR:) forControlEvents:UIControlEventTouchUpInside];
//        cell.txtLimitMin.hidden = self.segmIsIndex == 0;
//        cell.txtLimitMax.hidden = self.segmIsIndex == 0;
//        cell.label_.hidden = self.segmIsIndex == 0;
//        cell.labelDes.hidden = self.segmIsIndex == 0;
        
        return cell;
    }
    return [UITableViewCell new];
}



-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:NO];
}

#pragma mark - segmValueChanage

///求购售出列表类型
-(void)segmentValueChanged:(UISegmentedControl*)sender{
    self.segmIsIndex = sender.selectedSegmentIndex;

    JiaoYiMMListTableViewCell *cell = [self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:2 inSection:0]];
//    cell.txtLimitMin.hidden = self.segmIsIndex == 0;
//    cell.txtLimitMax.hidden = self.segmIsIndex == 0;
//    cell.label_.hidden = self.segmIsIndex == 0;
//    cell.labelDes.hidden = self.segmIsIndex == 0;
    NSString *strTitle = self.segmIsIndex == 0 ? @"确认买入":@"确认卖出";
    [cell.btnSubmitMM setTitle:strTitle forState:UIControlStateNormal];
}

#pragma mark - 购买
///购买买入提交按钮
-(void)btnSubmitMR:(UIButton*)sender{
    
//    JiaoYiMMListTableViewCell *cell = [self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:2 inSection:0]];
    
//    if ([cell.txtNumber.text integerValue] < 100 || [cell.txtNumber.text integerValue] > 2000 ) {
//        [DKProgressHUD showErrorWithStatus:@"请输入100-2000个范围的chinaa"];
//        return;
//    }
//    if (self.segmIsIndex != 0 ) {
//        [DKProgressHUD showErrorWithStatus:@"请输入正确的限额"];
//        return;
        
//    }
    
    if ([[UserCenter shareCenter].user.IsIdentification isEqualToString:@"20060004"] || [[UserCenter shareCenter].user.IsIdentification isEqualToString:@"20060003"]) {
        [self.navigationController pushViewController:[MeAuthenticationViewController new] animated:YES];
        return;
    }else if ([[UserCenter shareCenter].user.IsIdentification isEqualToString:@"20060001"]){
        [DKProgressHUD showErrorWithStatus:@"实名认证成功后才可以操作"];
        return;
    }
   
    ///进入输入密码的模块
    self.viewPassword.hidden = NO;
    __block JiaoYiPageViewController *  blockSelf = self;
    self.viewPassword.blockSubmit = ^(NSString *pwd) {
        blockSelf.strPayPwd = pwd;
//        JiaoYiMMTableViewCell *cell = [blockSelf.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:2]];
//
//        blockSelf.viewPassword.hidden = YES;
//        blockSelf.viewPassword.txtPwd.text = @"";
//
//        blockSelf.viewConfrimInfo.hidden = NO;
//
//        blockSelf.viewConfrimInfo.labelNumber.text = [NSString stringWithFormat:@"%@ GTE",cell.viewJY.txtMRNumber.text];
//        blockSelf.viewConfrimInfo.labelMJ.text = [NSString stringWithFormat:@"%@ CNY",cell.viewJY.txtMRPrice.text];
//        blockSelf.viewConfrimInfo.labelZJ.text = cell.viewJY.labelHeJi.text;
//        blockSelf.viewConfrimInfo.labelXE.text =  [NSString stringWithFormat:@"%@ CNY",cell.viewJY.txtMRXE.text];
        
//        [blockSelf.viewConfrimInfo.btnConfrim addTarget:blockSelf action:@selector(btnInfoConfrim:) forControlEvents:UIControlEventTouchUpInside];
        [blockSelf btnInfoConfrim:nil];
    };
}

///确认信息后点击提示
-(void)btnInfoConfrim:(UIButton*)sender{
    NSLog(@"确认过信息");
    self.viewConfrimInfo.hidden = YES;
    
    JiaoYiMMListTableViewCell *cell = [self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:2 inSection:0]];
    
    CGFloat sNumber = [cell.txtNumber.text floatValue];
    CGFloat sPrice = [cell.txtPrice.text floatValue];
    
    NSMutableDictionary *dict = [NSMutableDictionary new];
    [dict setValue:@(sPrice) forKey:@"pricermb"];
    [dict setValue:@(sNumber) forKey:@"bicount"];
    //限额作废，暂时存储最大默认值
    [dict setValue:@(0) forKey:@"limitmix"];
    [dict setValue:@(sNumber) forKey:@"limitmax"];
    
    NSInteger indexType = self.segmIsIndex == 0 ? 1 : 0;
    [dict setValue:@(indexType) forKey:@"ordertype"];
    
    [dict setValue:self.strPayPwd forKey:@"paypwd"];
    
//    [DKProgressHUD showLoading];
    [taskJiaoYiService addTransOrder:dict success:^(BaseModel *response, BOOL success) {
        [DKProgressHUD dismiss];
        if (success) {
            [DKProgressHUD showSuccessWithStatus:@"发布成功"];
            JiaoYiSuccessViewController *vc = [JiaoYiSuccessViewController new];
            vc.isMaiRu = self.segmIsIndex == 0 ? YES : NO;
            [self.navigationController pushViewController:vc animated:YES];
            return;
        }
        [DKProgressHUD showErrorWithStatus:response.message];
    } failture:^(NSError *error, NSString *strDescription) {
        [DKProgressHUD dismiss];
        [DKProgressHUD showErrorWithStatus:strDescription];
    }];
}

-(void)orderAction{
    [self.navigationController pushViewController:[JiaoYiOrderViewController new] animated:YES];
}


#pragma mark - touch view

-  (void)touchesEnded:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    [self.view endEditing:YES];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
@end
